from typing import Optional, List
from django.db.models import Q
from ..models.problem_model import ProblemModel, TagModel, TypeModel

class ProblemService:
    @staticmethod
    def get_problems(
        page: int = 1,
        page_size: int = 10,
        search: Optional[str] = None,
        tag_id: Optional[int] = None,
        type_id: Optional[int] = None,
        ordering: str = '-create_time'
    ) -> List[ProblemModel]:
        """获取题目列表"""
        queryset = ProblemModel.objects.filter(is_delete=False)

        # 关键词搜索
        if search:
            queryset = queryset.filter(
                Q(title__icontains=search) |
                Q(problem_description__icontains=search)
            )

        # 标签筛选
        if tag_id:
            queryset = queryset.filter(tag_id=tag_id)

        # 类型筛选
        if type_id:
            queryset = queryset.filter(type_id=type_id)

        # 分页
        start = (page - 1) * page_size
        end = start + page_size
        queryset = queryset.order_by(ordering)
        return queryset[start:end]

    @staticmethod
    def get_problem(problem_id: int) -> Optional[ProblemModel]:
        """获取题目详情"""
        try:
            return ProblemModel.objects.get(id=problem_id, is_delete=False)
        except ProblemModel.DoesNotExist:
            return None

    @staticmethod
    def create_problem(**data) -> ProblemModel:
        """创建题目"""
        return ProblemModel.objects.create(**data)

    @staticmethod
    def update_problem(problem_id: int, **data) -> Optional[ProblemModel]:
        """更新题目"""
        try:
            problem = ProblemModel.objects.get(id=problem_id, is_delete=False)
            for key, value in data.items():
                if key == 'tag':
                    setattr(problem, key, TagModel.objects.get(id=value))
                elif key == 'type':
                    setattr(problem, key, TypeModel.objects.get(id=value))
                else:
                    setattr(problem, key, value)
            problem.save()
            return problem
        except ProblemModel.DoesNotExist:
            return None

    @staticmethod
    def delete_problem(problem_id: int) -> bool:
        """删除题目（软删除）"""
        try:
            problem = ProblemModel.objects.get(id=problem_id, is_delete=False)
            problem.is_delete = True
            problem.save()
            return True
        except ProblemModel.DoesNotExist:
            return False

    def get_problem_types(self):
        type_objs = TypeModel.objects.all()
        types = []
        for type_obj in type_objs:
            types.append({
                'id': type_obj.id,
                'name': type_obj.name
            })
        return types

    def get_problem_tags(self):
        tag_objs = TagModel.objects.all()
        tags = []
        for tag_obj in tag_objs:
            tags.append({
                'id': tag_obj.id,
                'name': tag_obj.name
            })
        return tags

    def save_problem(self, problem_id=None, **data):
        """Create or update a problem based on the presence of problem_id"""
        if problem_id:
            # Update existing problem
            return self.update_problem(problem_id, **data)
        else:
            # Create a new problem
            return self.create_problem(**data)